<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!--添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格 (selection-type="false"去掉插件默认的勾选框,expand-type="false"去掉插件默认的展开列, show-index展示索引值,show-row-hover="false"鼠标悬停时，移除当前行的高亮)-->
      <tree-table
        :data="catList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        border
        :show-row-hover="false"
        class="treeTable"
      >
        <!-- 是否有效 -->
        <template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            style="color: green"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="active" slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="editDialog(scope.row.cat_id)"
          >
            编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="editDialogDelete(scope.row.cat_id)"
          >
            删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加商品弹框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form
        :model="addDialogForm"
        :rules="addDialogFormRules"
        ref="addDialogFormRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addDialogForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- options指定数据源 -->
          <!-- props用来指定配置对象 -->
          <el-cascader
            v-model="selectedKeys"
            :options="parentList"
            :props="cascaderProps"
            expand-trigger="hover"
            @change="parentChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogTrue">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑弹框 -->
    <el-dialog title="修改分类" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="editDialogForm"
        :rules="editDialogFormRules"
        ref="editDialogFormRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editDialogForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialogTrue">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Categories',
  data() {
    return {
      // 查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      catList: [],
      total: 0,
      // 为tree-table指定列的定义
      columns: [
        {
          // 指定标题
          label: '分类名称',
          // 指定具体值
          prop: 'cat_name',
        },
        {
          // 指定标题
          label: '是否有效',
          // 当前列定义为模板列
          type: 'template',
          // 当前列使用模板名称
          template: 'isOk',
        },
        {
          // 指定标题
          label: '排序',
          // 当前列定义为模板列
          type: 'template',
          // 当前列使用模板名称
          template: 'order',
        },
        {
          // 指定标题
          label: '操作',
          // 当前列定义为模板列
          type: 'template',
          // 当前列使用模板名称
          template: 'active',
        },
      ],
      addDialogVisible: false,
      addDialogForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0,
      },
      addDialogFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
      },
      // 父级分类的列表
      parentList: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 选中的父级分类的的Id数组
      selectedKeys: [],
      editDialogVisible: false,
      editDialogForm: {},
      editDialogFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getCatList()
  },
  methods: {
    async getCatList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.catList = res.data.result
      this.total = res.data.total
    },
    // 监听pagesize改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCatList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCatList()
    },
    addDialog() {
      // 获取父级分类的数据列表
      this.getParentList()
      this.addDialogVisible = true
    },
    // 获取父级分类的数据列表
    async getParentList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.parentList = res.data
    },
    // 选择项发生变化时触发
    parentChange() {
      // 如果selectedKeys数组的length大于0，证明选中了父级分类，反之没有选中父级分类
      if (this.selectedKeys.length > 0) {
        // 父级分类的Id
        this.addDialogForm.cat_pid =
          this.selectedKeys[this.selectedKeys.length - 1]
        // 等级赋值
        this.addDialogForm.cat_level = this.selectedKeys.length
        return
      } else {
        this.addDialogForm.cat_pid = 0
        this.addDialogForm.cat_level = 0
      }
    },
    addDialogTrue() {
      this.$refs.addDialogFormRef.validate(async (val) => {
        if (!val) return
        const { data: res } = await this.$http.post(
          'categories',
          this.addDialogForm
        )
        if (res.meta.status !== 201) {
          return this.$message.error('获取数据失败')
        }
        this.$message.success('获取数据成功')
        this.getCatList()
        this.addDialogVisible = false
      })
    },
    addDialogClose() {
      this.$refs.addDialogFormRef.resetFields()
      this.selectedKeys = []
      this.addDialogForm.cat_pid = 0
      this.addDialogForm.cat_level = 0
    },
    async editDialog(id) {
      const { data: res } = await this.$http.get('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.editDialogForm = res.data
      this.editDialogVisible = true
    },
    editDialogTrue() {
      this.$refs.editDialogFormRef.validate(async (val) => {
        if (!val) return
        const { data: res } = await this.$http.put(
          'categories/' + this.editDialogForm.cat_id,
          {
            cat_id: this.editDialogForm.cat_id,
            cat_name: this.editDialogForm.cat_name,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改数据失败')
        }
        this.$message.success('修改数据成功')
        this.getCatList()
        this.editDialogVisible = false
      })
    },
    async editDialogDelete(id) {
      const result = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => {
        return error
      })
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除数据失败')
      }
      this.$message.success('删除数据成功')
      this.getCatList()
    },
  },
}
</script>

<style scope>
.treeTable {
  margin-top: 20px;
}
.el-cascader {
  width: 100%;
}
/* 定义级联选择器的高度 */
.el-cascader-menu {
  height: 400px;
}
</style>